package com.example.certificate.service.impl;

import com.example.certificate.entity.WakeFile;
import com.example.certificate.mapper.WakeFileMapper;
import com.example.certificate.service.WakeFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.certificate.utils.FileUtils;
import com.example.certificate.utils.ResultEntity;
import com.qcloud.cos.auth.BasicCOSCredentials;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.utils.IOUtils;

@Service
public class WakeFileServiceImpl extends ServiceImpl<WakeFileMapper, WakeFile> implements WakeFileService {

    @Value("${cos.bucket}")
    private String BUCKET_NAME;

    @Resource
    private WakeFileMapper wakeFileMapper;

    private COSClient cosClient;

    @PostConstruct
    public void init() {
        // 初始化 COS 客户端
        ClientConfig clientConfig = new ClientConfig(new Region("ap-chongqing"));
        BasicCOSCredentials cred = new BasicCOSCredentials("AKIDeATYP3nVAdt18A0dmrGZggUlupW6Y8oN", "VTL0Ut7EAtPmywxmU1KPI3e4KVYQ4UnG");
        cosClient = new COSClient(cred, clientConfig);
    }

    @PreDestroy
    public void cleanup() {
        // 关闭 COS 客户端
        if (cosClient != null) {
            cosClient.shutdown();
        }
    }

    @Override
    public ResultEntity uploadFile(MultipartFile file) throws Exception {
        String fileName= FileUtils.getRandomImgName(file.getOriginalFilename());
        Long fileSize = file.getSize();

        File localFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), fileName);
        file.transferTo(localFile);

        PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, fileName, localFile);
        cosClient.putObject(putObjectRequest);

        return insertFileInfos(file.getOriginalFilename(), fileName, fileSize);
    }

    @Override
    public ResponseEntity<ByteArrayResource> download(String fileName) throws IOException {
        COSObject cosObject = cosClient.getObject(BUCKET_NAME, fileName);
        COSObjectInputStream inputStream = cosObject.getObjectContent();
        ByteArrayResource resource = new ByteArrayResource(IOUtils.toByteArray(inputStream));

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(cosObject.getObjectMetadata().getContentLength())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

    public ResultEntity insertFileInfos(String originalName, String fileName, Long size) {
        String suffix = originalName.substring(originalName.lastIndexOf(".") + 1);
        String perFix = originalName.substring(0,originalName.lastIndexOf("."));

        WakeFile wakeFile = new WakeFile();
        wakeFile.setFileOriginName(originalName);
        wakeFile.setFileName(fileName);
        wakeFile.setFileSize(size);
        wakeFile.setFilePrefix(perFix);
        wakeFile.setFileSuffix(suffix);

        Integer fileType = FileUtils.hashMap.get(suffix);
        if(StringUtils.hasLength(fileType.toString())){
            wakeFile.setFileType(fileType);
        } else {
            wakeFile.setFileType(5);
        }

        wakeFile.setFileUrl("https://wyd-1327159930.cos.ap-chongqing.myqcloud.com/" + fileName);

        return new ResultEntity(wakeFile);
    }
}
